package com.esun.payment_api.service.impl;


import com.esun.common.api.CommonResult;
import com.esun.common.utils.BlankUtils;
import com.esun.payment_api.bean.*;
import com.esun.payment_api.domain.*;
import com.esun.payment_api.mapper.*;
import com.esun.payment_api.service.DkClaimService;
import com.esun.payment_api.service.LogService;
import com.esun.payment_api.service.XcxInfoService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class DkClaimServiceImpl implements DkClaimService {
    @Resource
    DkClaimMapper dkClaimMapper;

    @Resource
    DkClaimInvoiceMapper dkClaimInvoiceMapper;

    @Resource
    DkClaimContractMapper dkClaimContractMapper;

    @Resource
    DkClaimTaskMapper dkClaimTaskMapper;

    @Resource
    DkReceiveMapper dkReceiveMapper;

    @Resource
    SysDictDataMapper sysDictDataMapper;

    @Resource
    DkClaimCancelMapper dkClaimCancelMapper;

    @Resource
    XcxInfoService xcxInfoService;

    @Resource
    LogService logService;
    final String moduleName = "到款认领";

//    @Override
//    public CommonResult claimReceive(Short receiveId, User user){
//        try{
//            DkReceive dkReceive = dkReceiveMapper.selectByPrimaryKey(receiveId);
//            if(dkReceive==null){
//                return CommonResult.failed("未找到此条到款记录");
//            }
//            DkClaim dkClaim = new DkClaim();
//            dkClaim.setReceiveId(receiveId);
//            dkClaim.setFlowStatus("1");
//            dkClaim.setReceiveMoney(dkReceive.getMoney());
//            dkClaim.setClaimMoney(BigDecimal.ZERO);
//            dkClaim.setInvoiceMoney(BigDecimal.ZERO);
//            dkClaim.setPayableMoney(BigDecimal.ZERO);
//            dkClaim.setCoId(user.getCoId());
//            dkClaim.setOpDeptId(user.getDeptId());
//            dkClaim.setBankType(dkReceive.getBankType());
//            Date date = new Date();
//            dkClaim.setClaimDate(date);
//            dkClaim.setCreateBy(user.getId());
//            dkClaim.setOperatorId(user.getId());
//            return addOrEditDkClaim(dkClaim);
//        }catch (Exception e){
//            System.out.println(e.getMessage());
//            return CommonResult.failed("认领到款记录失败，参考原因"+e.getMessage());
//        }
//
//    }

    @Override
    public CommonResult claimReceive(Integer receiveId, User user){
        try{
            Map<String,String> map = new HashMap<>();
            map.put("receiveId",receiveId.toString());
            map.put("companyId",user.getCoId().toString());
            map.put("userId",user.getId().toString());
            dkReceiveMapper.claimReceive(map);
            Integer claimId = Integer.valueOf(map.get("claimId"));
            return CommonResult.success(claimId, "认领到款成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领到款记录失败claimReceive，参考原因"+e.getMessage(), moduleName);
            return CommonResult.failed("认领到款记录失败：claimReceive");
        }

    }


    @Override
    public CommonResult saveClaim(DkClaim dkClaim, User user){
        dkClaim.setOperatorId(user.getId());
        dkClaim.setCoId(user.getCoId());
        dkClaim.setOpDeptId(user.getDeptId());
        //这里应该加入对于两种Money的更新。
        return addOrEditDkClaim(dkClaim);
    }

    @Override
    public CommonResult submitClaim(DkClaim dkClaim, User user){
        try{
            addOrEditDkClaim(dkClaim);
            String result = dkClaimMapper.checkClaim(dkClaim.getId());
            if("1".equals(result)){
                DkClaim dkClaim2 = dkClaimMapper.selectByPrimaryKey(dkClaim.getId());
                DkReceive dkReceive = dkReceiveMapper.selectByPrimaryKey(dkClaim2.getReceiveId());
                if(dkClaim2==null || dkReceive ==null){
                    return CommonResult.failed("无法找到本条到款认领记录，提交到款认领失败");
                }
                BigDecimal totalClaimedMoney = dkClaimMapper.getTotalClaimedMoney(dkClaim2.getReceiveId(), user.getCoId(), dkClaim2.getId());
                BigDecimal unclaimedMoney = (dkReceive.getMoney().subtract(totalClaimedMoney));

                if ("13".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为纵向WQ 13
                    dkClaimMapper.submitClaimYwlxIsZxWQ(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 426, dkClaim.getId());
                } else if ("12".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为纵向YH 12
                    dkClaimMapper.submitClaimYwlxIsZxYH(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 425, dkClaim.getId());
                } else if ("11".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为考试费 11
                    dkClaimMapper.submitClaimYwlxIsKsf(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 405, dkClaim.getId());
                } else if ("4".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为非主业收款 4 改为版面费
                    dkClaimMapper.submitClaimYwlxIsBmf(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 381, dkClaim.getId());
                } else if ("8".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为其他 8
                    dkClaimMapper.submitClaimYwlxIsQt(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 361, dkClaim.getId());
                } else if ("2".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为纵向 2
                    dkClaimMapper.submitClaimYwlxIsZx(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 341, dkClaim.getId());
                } else if (user.getDeptId() == (short) 90) {
                    //如果申请人部门为研究发展处 id=90
                    dkClaimMapper.submitClaimDeptIsYfc(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 301, dkClaim.getId());
                } else if (dkClaim2.getReceiveMoney().equals(dkClaim.getClaimMoney()) && dkClaim2.getPayableMoney() == BigDecimal.valueOf(0)) {
//                    对于预收金额=0的所有单据，视有无发票（已在线下开票也算有发票）
//                    有无合同、是否为汇票（Bank_TYPE是1、2则不是汇票）遵循以下规则
                    //发票	    合同	    汇票	    类型
                    //是		是		是		汇票简化审批 - 财务负责人
                    //是		是		否		到款认领审批（无发票）- 业务财务，横向提交直接通过（20230920修改）
                    //是		否		是		到款认领审批（无合同） - 部门领导，主管部门，财务负责人
                    //是		否		否		到款认领审批（无合同） - 部门领导，主管部门，财务负责人
                    //否		是		是		汇票简化审批（无发票）- 财务负责人，业务财务
                    //否		是		否		到款认领审批（无发票）- 业务财务
                    //否		否		是		部门领导，主管部门，财务负责人，业务财务 = 全流程
                    //否		否		否		部门领导，主管部门，财务负责人，业务财务 = 全流程

                    //需要发票
                    if (dkClaim2.getNeedInvoice() == 1 || dkClaim2.getWhyNoInvoice().equals("已在线下开票")) {
                        //需要关联合同
                        if (dkClaim2.getNeedContract() == 1) {
                            //工行或建行
                            if (dkClaim2.getBankType() == 1 || dkClaim2.getBankType() == 2) {
                                //如果业务类型是横向 1  直接通过，否则业务财务审批
                                if ("1".equals(dkClaim2.getBusinessType())) {
                                    //直接通过审批
                                    dkClaim.setFlowStatus("4");
                                    Date date = new Date();
                                    dkClaim.setClaimDate(date);
                                    dkClaimMapper.updateByPrimaryKeySelective(dkClaim);
                                    //已认领后，生成电子回单
                                    dkClaimMapper.addBankReceipt(dkClaim.getId());
                                } else {
                                    dkClaimMapper.submitClaimNoInvoice(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                    xcxInfoService.getFlowIdAndSend((short) 141, dkClaim.getId());
                                }
                            } else {
                                dkClaimMapper.submitClaimSimplified(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                xcxInfoService.getFlowIdAndSend((short) 121, dkClaim.getId());
                            }
                        } else {
                            dkClaimMapper.submitClaimNoContract(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                            xcxInfoService.getFlowIdAndSend((short) 181, dkClaim.getId());
                        }
                    } else {
                        if (dkClaim2.getNeedContract() == 1) {
                            if (dkClaim2.getBankType() == 1 || dkClaim2.getBankType() == 2) {
                                dkClaimMapper.submitClaimNoInvoice(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                xcxInfoService.getFlowIdAndSend((short) 141, dkClaim.getId());
                            } else {
                                dkClaimMapper.submitClaimSimplifiedNoInvoice(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                xcxInfoService.getFlowIdAndSend((short) 142, dkClaim.getId());
                            }
                        } else {
                            dkClaimMapper.submitClaim(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                            xcxInfoService.getFlowIdAndSend((short) 81, dkClaim.getId());
                        }
                    }

                } else {
                    dkClaimMapper.submitClaim(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 81, dkClaim.getId());
                }
                return CommonResult.success(null, "提交到款认领成功");

            } else {
                return CommonResult.failed(result);
            }

        } catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("提交到款认领失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("提交到款认领失败");
        }
    }

    @Override
    public CommonResult resubmitClaim(DkClaim dkClaim, User user){
        try{
            addOrEditDkClaim(dkClaim);
            String result = dkClaimMapper.checkClaim(dkClaim.getId());
            if(result.equals("1")){
                DkClaim dkClaim2 = dkClaimMapper.selectByPrimaryKey(dkClaim.getId());
                DkReceive dkReceive = dkReceiveMapper.selectByPrimaryKey(dkClaim2.getReceiveId());
                if(dkClaim==null || dkReceive ==null){
                    return CommonResult.failed("无法找到本条到款认领记录，重新提交到款认领失败");
                }
                BigDecimal totalClaimedMoney = dkClaimMapper.getTotalClaimedMoney(dkClaim2.getReceiveId(), user.getCoId(), dkClaim2.getId());
                BigDecimal unclaimedMoney = (dkReceive.getMoney().subtract(totalClaimedMoney));
                if ("13".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为纵向WQ 13
                    dkClaimMapper.resubmitClaimYwlxIsZxWQ(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 426, dkClaim.getId());
                } else if ("12".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为纵向YH 12
                    dkClaimMapper.resubmitClaimYwlxIsZxYH(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 425, dkClaim.getId());
                } else if ("11".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为考试费 11
                    dkClaimMapper.resubmitClaimYwlxIsKsf(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 405, dkClaim.getId());
                } else if ("4".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为非主业收款 4  改为版面费
                    dkClaimMapper.resubmitClaimYwlxIsBmf(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 381, dkClaim.getId());
                } else if ("8".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为其他 8
                    dkClaimMapper.resubmitClaimYwlxIsQt(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 361, dkClaim.getId());
                } else if ("2".equals(dkClaim2.getBusinessType())) {
                    //如果业务类型为纵向 2
                    dkClaimMapper.resubmitClaimYwlxIsZx(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 341, dkClaim.getId());
                } else if (user.getDeptId() == (short) 90) {
                    //如果申请人部门为研究发展处 id=90
                    dkClaimMapper.resubmitClaimDeptIsYfc(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 301, dkClaim.getId());
                } else if (dkClaim2.getReceiveMoney().equals(dkClaim.getClaimMoney()) && dkClaim2.getPayableMoney() == BigDecimal.valueOf(0)) {
                    // 如果本次认领全部剩余到款，银行来款则自动通过，承兑汇票走简化流程
                    if (dkClaim2.getNeedInvoice() == 1 || dkClaim2.getWhyNoInvoice().equals("已在线下开票")) {
                        if (dkClaim2.getNeedContract() == 1) {
                            //工行或建行
                            if (dkClaim2.getBankType() == 1 || dkClaim2.getBankType() == 2) {
                                //如果业务类型是横向 1  直接通过，否则业务财务审批
                                if ("1".equals(dkClaim2.getBusinessType())) {
                                    //直接通过审批
                                    dkClaim.setFlowStatus("4");
                                    Date date = new Date();
                                    dkClaim.setClaimDate(date);
                                    dkClaimMapper.updateByPrimaryKeySelective(dkClaim);
                                    //已认领后，生成电子回单
                                    dkClaimMapper.addBankReceipt(dkClaim.getId());
                                } else {
                                    dkClaimMapper.resubmitClaimNoInvoice(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                    xcxInfoService.getFlowIdAndSend((short) 141, dkClaim.getId());
                                }
                            } else {
                                dkClaimMapper.resubmitClaimSimplified(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                xcxInfoService.getFlowIdAndSend((short) 121, dkClaim.getId());
                            }
                        } else {
                            dkClaimMapper.resubmitClaimNoContract(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                            xcxInfoService.getFlowIdAndSend((short) 181, dkClaim.getId());
                        }
                    } else {
                        if (dkClaim2.getNeedContract() == 1) {
                            if (dkClaim2.getBankType() == 1 || dkClaim2.getBankType() == 2) {
                                dkClaimMapper.resubmitClaimNoInvoice(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                xcxInfoService.getFlowIdAndSend((short) 141, dkClaim.getId());
                            } else {
                                dkClaimMapper.resubmitClaimSimplifiedNoInvoice(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                                xcxInfoService.getFlowIdAndSend((short) 142, dkClaim.getId());
                            }
                        } else {
                            dkClaimMapper.resubmitClaim(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                            xcxInfoService.getFlowIdAndSend((short) 81, dkClaim.getId());
                        }
                    }

                } else {
                    dkClaimMapper.resubmitClaim(user.getCoId(), dkClaim2.getUuid(), dkClaim.getId(), user.getId(), user.getDeptId());
                    xcxInfoService.getFlowIdAndSend((short) 81, dkClaim.getId());
                }
                return CommonResult.success(null, "重新提交到款认领成功");
            } else {
                return CommonResult.failed(result);
            }

        } catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("重新提交到款认领失败，参考原因："+e.getMessage(), moduleName);
            return CommonResult.failed("重新提交到款认领失败");
        }
    }

    //新建或编辑到款认领记录，并返回记录的主键ID
    public CommonResult addOrEditDkClaim(DkClaim dkClaim){
        try{
            if(dkClaim.getId()==null){
                if(dkClaimMapper.insertSelectiveReturnId(dkClaim)<=0){
                    return CommonResult.failed("新建到款认领失败");
                }
            }else{
                if(dkClaimMapper.updateByPrimaryKeySelective(dkClaim)!=1){
                    return CommonResult.failed("更新到款认领失败");
                }
            }
            return CommonResult.success(dkClaim.getId(), "新建或更新到款记录成功");
        } catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("新建或更新到款记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("新建或更新到款记录失败");
        }
    }

    @Override
    public CommonResult cancelClaim(Integer claimId, User user){
        try{
            DkClaim dkClaim = dkClaimMapper.selectByPrimaryKey(claimId);
            if(dkClaim==null||dkClaim.getId()==null){
                return CommonResult.failed("取消到款认领记录失败，参考原因：数据库内无ID为"+claimId+"的记录");
            }
            dkClaim.setFlowStatus("0");
            CommonResult commonResult = addOrEditDkClaim(dkClaim);
            if(commonResult.getCode()!=200){
                return commonResult;
            }
            dkClaimMapper.cancelClaim(claimId, user.getCoId(), user.getId());
            return CommonResult.success(null, "取消到款认领成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("取消到款认领失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("取消到款认领失败");
        }

    }

    @Override
    public CommonResult claimRelateInvoice(String invoiceStr, Integer claimId, User user){
        try{
            dkClaimMapper.claimRelateInvoice(invoiceStr, claimId, user.getCoId(), user.getId());
            return CommonResult.success(null, "认领关联发票成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领关联发票失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("认领关联发票失败");
        }
    }

    @Override
    public CommonResult claimRelateContract(String contractStr, Integer claimId, User user){
        try{
            dkClaimMapper.claimRelateContract(contractStr, claimId, user.getCoId(), user.getId());
            return CommonResult.success(null, "认领关联合同成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领关联合同失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("认领关联合同失败");
        }
    }

    @Override
    public CommonResult claimRelateTask(String taskStr, Integer claimId, User user){
        try{
            dkClaimMapper.claimRelateTask(taskStr, claimId, user.getCoId(), user.getId());
            return CommonResult.success(null, "认领关联任务号成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领关联任务号失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("认领关联任务号失败");
        }
    }

    @Override
    public CommonResult claimCancelInvoice(String invoiceStr, Integer claimId, User user){
        try{
            //由于现在前端传来的是 认领-发票ID，所以必须先查出对应实体类，然后再取消关联。
            String[] strings = invoiceStr.split(":");
            List<Integer> idList = new ArrayList<>();
            for (String s : strings) {
                idList.add(Integer.valueOf(s));
            }
            DkClaimInvoiceExample example = new DkClaimInvoiceExample();
            DkClaimInvoiceExample.Criteria criteria = example.createCriteria();
            criteria.andClaimIdEqualTo(claimId);
            criteria.andIdIn(idList);
            List<DkClaimInvoice> dkClaimInvoiceList = dkClaimInvoiceMapper.selectByExample(example);
            for(DkClaimInvoice dkClaimInvoice : dkClaimInvoiceList){
                String invoiceIdStr = dkClaimInvoice.getInvId().toString();
                dkClaimMapper.claimCancelInvoice(invoiceIdStr, claimId, user.getCoId(), user.getId());
            }
            return CommonResult.success(null, "认领取消关联发票成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领取消关联发票失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("认领取消关联发票失败");
        }
    }

    @Override
    public CommonResult claimCancelContract(String contractStr, Integer claimId, User user){
        try{
            String[] strings = contractStr.split(":");
            List<Integer> idList = new ArrayList<>();
            for (String s : strings) {
                idList.add(Integer.valueOf(s));
            }
            DkClaimContractExample example = new DkClaimContractExample();
            DkClaimContractExample.Criteria criteria = example.createCriteria();
            criteria.andClaimIdEqualTo(claimId);
            criteria.andIdIn(idList);
            List<DkClaimContract> dkClaimContractList = dkClaimContractMapper.selectByExample(example);
            for(DkClaimContract dkClaimContract : dkClaimContractList){
                String contractIdStr = dkClaimContract.getContId().toString();
                dkClaimMapper.claimCancelContract(contractIdStr, claimId, user.getCoId(), user.getId());
            }
            return CommonResult.success(null, "认领取消关联合同成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领取消关联合同失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("认领取消关联合同失败，参考原因");
        }
    }

    @Override
    public CommonResult claimCancelTask(String taskStr, Integer claimId, User user){
        //现在删除的实现是按照传入记录ID来删，而不是任务ID。可能需要修改。看情况。
        try{
            String[] strings = taskStr.split(":");
            List<Integer> idList = new ArrayList<>();
            for (String s : strings) {
                idList.add(Integer.valueOf(s));
            }

//            dkClaimMapper.claimRelateTask(taskStr, claimId, user.getCoId(), user.getId());
            DkClaimTaskExample dkClaimTaskExample = new DkClaimTaskExample();
            DkClaimTaskExample.Criteria criteria = dkClaimTaskExample.createCriteria();
            criteria.andClaimIdEqualTo(claimId);
            criteria.andIdIn(idList);
            criteria.andIsDeletedEqualTo("0");
            List<DkClaimTask> dkClaimTaskList = dkClaimTaskMapper.selectByExample(dkClaimTaskExample);
            for (DkClaimTask dkClaimTask : dkClaimTaskList){
                dkClaimTask.setIsDeleted("1");
                dkClaimTaskMapper.updateByPrimaryKeySelective(dkClaimTask);
            }
            autoCalMoney(claimId);

            return CommonResult.success(null, "认领取消关联任务号成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领取消关联任务号失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("认领取消关联任务号失败");
        }
    }

    @Override
    public CommonResult editClaimInvoice(DkClaimInvoice dkClaimInvoice){
        try{
            if(dkClaimInvoiceMapper.updateByPrimaryKeySelective(dkClaimInvoice)!=1){
                return CommonResult.failed("更新认领-发票记录失败");
            }
            return CommonResult.success(null, "更新认领-发票记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("更新认领-发票记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("更新认领-发票记录失败");
        }
    }

    @Override
    public CommonResult editClaimContract(DkClaimContract dkClaimContract){
        try{
            if(dkClaimContractMapper.updateByPrimaryKeySelective(dkClaimContract)!=1){
                return CommonResult.failed("更新认领-合同记录失败");
            }
            return CommonResult.success(null, "更新认领-合同记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("更新认领-合同记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("更新认领-合同记录失败");
        }
    }

    @Override
    public CommonResult editClaimTask(DkClaimTask dkClaimTask){
        try{
            if(dkClaimTaskMapper.updateByPrimaryKeySelective(dkClaimTask)!=1){
                return CommonResult.failed("更新认领-任务号记录失败");
            }
            dkClaimTask = dkClaimTaskMapper.selectByPrimaryKey(dkClaimTask.getId());
            autoCalMoney(dkClaimTask.getClaimId());
            return CommonResult.success(null, "更新认领-任务号记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("更新认领-任务号记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("更新认领-任务号记录失败");
        }
    }

    @Override
    public List<DkReceiveBean> getUnclaimedList(User user, String searchStr, String monthStr, String bankType, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        return dkReceiveMapper.getUnclaimedList(user.getCoId(), user.getDeptId(), searchStr, monthStr, bankType);
    }

    @Override
    public List<DkReceiveBean> getUnclaimedListSubs(User user, String searchStr, String bankType, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        return dkReceiveMapper.getUnclaimedListSubs(user.getId(), user.getCoId(), user.getDeptId(), searchStr, bankType);
    }

    @Override
    public List<DkClaimBean> getClaimList(String flowStatus, String searchStr, String monthStr, String deptName, String startTime, String endTime, String receiveType, String businessType, User user, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        return dkClaimMapper.getDkClaimDataList(user.getId(), user.getDeptId(), user.getCoId(), searchStr, flowStatus, null, monthStr, deptName, startTime, endTime, receiveType, businessType);
    }

    @Override
    public SumDkReceiveMoneyBean getSumDkClaimMoney(String flowStatus, String searchStr, String monthStr, String deptName, String startTime, String endTime, String receiveType, String businessType, User user){
     return dkClaimMapper.getDkClaimDataSum(user.getId(), user.getDeptId(), user.getCoId(), searchStr, flowStatus, null, monthStr, deptName, startTime, endTime, receiveType, businessType);
    }

    @Override
    public CommonResult getClaimById(User user, Integer claimId){
        try {
            return CommonResult.success(dkClaimMapper.getDkClaimData(user.getId(), user.getDeptId(), user.getCoId(), null, null, claimId, null, null, null, null, null, null), "获取ID为"+claimId+"的认领记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取ID为"+claimId+"的认领记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领记录失败");
        }
    }

    @Override
    public CommonResult getClaimInvoiceById(User user, Integer claimInvoiceId){
        try {
            DkClaimInvoice dkClaimInvoice = dkClaimInvoiceMapper.selectByPrimaryKey(claimInvoiceId);
            return CommonResult.success(dkClaimInvoiceMapper.getClaimInvoiceById(user.getCoId(), dkClaimInvoice.getClaimId(), claimInvoiceId), "获取ID为"+claimInvoiceId+"的认领-发票关联记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取ID为"+claimInvoiceId+"的认领-发票关联记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领-发票关联记录失败");
        }
    }

    @Override
    public CommonResult getClaimContractById(Integer claimContractId){
        try {
            return CommonResult.success(dkClaimContractMapper.getClaimContractData(null,claimContractId), "获取ID为"+claimContractId+"的认领-合同关联记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取ID为"+claimContractId+"的认领-合同关联记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领-合同关联记录失败");
        }
    }

    @Override
    public CommonResult getClaimTaskById(Integer claimTaskId){
        try {
            return CommonResult.success(dkClaimTaskMapper.getClaimTaskData(null, claimTaskId), "获取ID为"+claimTaskId+"的认领-任务关联记录成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取ID为"+claimTaskId+"的认领-任务关联记录失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领-任务关联记录失败");
        }
    }

    @Override
    public CommonResult getClaimInvoiceByClaimId(User user, Integer claimId){
        try {
            return CommonResult.success(dkClaimInvoiceMapper.getClaimInvoiceByClaimId(user.getCoId(), claimId), "获取认领已关联发票清单成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取认领已关联发票清单失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领已关联发票清单失败");
        }
    }

    @Override
    public CommonResult getClaimContractByClaimId(Integer claimId){
        try {
            return CommonResult.success(dkClaimContractMapper.getClaimContractData(claimId,null), "获取认领已关联合同清单成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取认领已关联合同清单失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领已关联合同清单失败");
        }
    }

    @Override
    public CommonResult getClaimTaskByClaimId(Integer claimId){
        try {
            return CommonResult.success(dkClaimTaskMapper.getClaimTaskData(claimId, null), "获取认领已关联任务清单成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取认领已关联任务清单失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领已关联任务清单失败");
        }
    }

    @Override
    public CommonResult getFlowByClaimId(User user, Integer claimId){
        try {
            List<DkFlowBean> list = dkClaimMapper.getFlowByClaimId(claimId, user.getCoId());
            List<DkFlowBean> applicationList = dkClaimMapper.getApplicationFlowByClaimId(claimId);
            if(applicationList.size()==0){
                System.out.println("获取发起人流程不成功");
                return CommonResult.success(list);
            }else{
                applicationList.addAll(list);
            }
            return CommonResult.success(applicationList, "获取认领流程清单成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取认领流程清单失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领流程清单失败");
        }
    }

    @Override
    public CommonResult rejectClaim(User user, Integer flowId, Integer claimId, String flowNotes){
        try {
            dkClaimMapper.rejectClaim(flowId,claimId, flowNotes, user.getId());
            return CommonResult.success(null, "驳回认领流程成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("驳回认领流程失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("驳回认领流程失败");
        }
    }

    @Override
    public CommonResult approveClaim(User user, Integer flowId, Integer claimId, String flowNotes){
        try {
            dkClaimMapper.approveClaim(flowId,claimId, flowNotes, user.getId());

            xcxInfoService.sendWxMessage(flowId);
            return CommonResult.success(null, "通过认领流程成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            logService.writeErrorLog("通过认领流程失败，参考原因："+e.getMessage(),moduleName);
            return CommonResult.failed("通过认领流程失败");
        }
    }

    @Override
    public CommonResult autoCalMoney(Integer claimId){
        try{
            dkClaimMapper.autoCalMoney(claimId);
            return CommonResult.success(null, "自动汇总金额成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("自动汇总金额失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("自动汇总金额失败");
        }
    }

    @Override
    public CommonResult getReceiveTypeDict(User user, String searchStr){
        SysDictDataExample example = new SysDictDataExample();
        SysDictDataExample.Criteria criteria = example.createCriteria();
        criteria.andCoIdEqualTo(user.getCoId());
        criteria.andDictTypeEqualTo("RECEIVE_TYPE");
        criteria.andIsDeletedEqualTo("0");
        if(!BlankUtils.isBlank(searchStr)){
            criteria.andDictValueLike("%"+searchStr+"%");
        }
        return CommonResult.success(sysDictDataMapper.selectByExample(example), "获取到款类型字典成功");

    }

    @Override
    public CommonResult getResponsibleDeptDict(User user, String searchStr){
        SysDictDataExample example = new SysDictDataExample();
        SysDictDataExample.Criteria criteria = example.createCriteria();
        criteria.andCoIdEqualTo(user.getCoId());
        criteria.andDictTypeEqualTo("RESPONSIBLE_DEPT");
        criteria.andIsDeletedEqualTo("0");
        if(!BlankUtils.isBlank(searchStr)){
            criteria.andDictValueLike("%"+searchStr+"%");
        }
        return CommonResult.success(sysDictDataMapper.selectByExample(example), "获取归口部门字典成功");

    }

    @Override
    public CommonResult abolishClaim(User user, DkClaimCancel dkClaimCancel){
        try{
            Map<String,String> map = new HashMap<>();
            map.put("claimId",dkClaimCancel.getClaimId().toString());
            map.put("reason",dkClaimCancel.getReason());
            map.put("userId",user.getId().toString());
            dkClaimCancelMapper.abolishClaim(map);
            DkClaim dkClaim = dkClaimMapper.selectByPrimaryKey(dkClaimCancel.getClaimId());
            if(dkClaim.getFlowStatus().equals("3")){
                return CommonResult.success(null, "认领废除成功");
            } else if(dkClaim.getFlowStatus().equals("4")){
                Integer abolishId = Integer.valueOf(map.get("abolishId"));
                return CommonResult.success(abolishId, "创建认领废除记录成功");
            } else {
                System.out.println("检测到 异常");
                return CommonResult.success(null, "创建认领废除记录成功");
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("创建废除认领记录失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("创建废除认领记录失败");
        }
    }

    @Override
    public CommonResult saveAbolishClaim(User user, DkClaimCancel dkClaimCancel){
        try{
            dkClaimCancelMapper.updateByPrimaryKeySelective(dkClaimCancel);
            return CommonResult.success(null,"暂存作废记录成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("暂存认领作废记录失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("暂存认领作废记录失败");
        }
    }

    @Override
    public CommonResult submitAbolishClaim(User user, DkClaimCancel dkClaimCancel){
        try{
            DkClaimCancel dkClaimCancel2 = dkClaimCancelMapper.selectByPrimaryKey(dkClaimCancel.getId());
            dkClaimCancelMapper.submitAbolishClaim(user.getCoId(),dkClaimCancel2.getUuid(),dkClaimCancel2.getId(),user.getId(),user.getDeptId());
            dkClaimCancelMapper.updateByPrimaryKeySelective(dkClaimCancel);

            xcxInfoService.getFlowIdAndSend((short)101, dkClaimCancel.getId());
            return CommonResult.success(null,"提交认领作废成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("提交认领作废失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("提交认领作废失败");
        }
    }

    @Override
    public CommonResult resubmitAbolishClaim(User user, DkClaimCancel dkClaimCancel){
        try{
            DkClaimCancel dkClaimCancel2 = dkClaimCancelMapper.selectByPrimaryKey(dkClaimCancel.getId());
            dkClaimCancelMapper.resubmitAbolishClaim(user.getCoId(),dkClaimCancel2.getUuid(),dkClaimCancel2.getId(),user.getId(),user.getDeptId());
            dkClaimCancelMapper.updateByPrimaryKeySelective(dkClaimCancel);

            xcxInfoService.getFlowIdAndSend((short)101, dkClaimCancel.getId());
            return CommonResult.success(null,"重新提交认领作废成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("重新提交认领作废失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("重新提交认领作废失败");
        }
    }

    @Override
    public CommonResult cancelClaimAbolish(User user, Integer abolishId){
        try{
            dkClaimCancelMapper.cancelClaimAbolish(abolishId, user.getId());
            return CommonResult.success(null, "取消认领作废成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("取消认领作废失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("取消废除认领失败");
        }
    }

    @Override
    public List<DkClaimAbolishBean> getClaimAbolishDataList(User user, String searchStr,
                                                            String flowStatus, String monthStr,
                                                            String deptName, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        return dkClaimCancelMapper.getClaimAbolishData(user.getCoId(), user.getDeptId(),
                user.getId(), searchStr,
                monthStr, deptName,
                flowStatus,null);
    }

    @Override
    public CommonResult getClaimAbolishDataById(User user, Integer abolishId){
        try{
            return CommonResult.success(dkClaimCancelMapper.getClaimAbolishData(user.getCoId(), user.getDeptId(), user.getId(), null, null, null,null,abolishId));
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取认领作废详情失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领作废详情失败");
        }
    }

    @Override
    public CommonResult getClaimAbolishFlow(User user, Integer abolishId){
        try{

            List<DkFlowBean> list = dkClaimCancelMapper.getClaimAbolishFlow(user.getCoId(), abolishId);
            List<DkFlowBean> applicationList = dkClaimCancelMapper.getApplicationFlowByAbolishId(abolishId);
            if(applicationList.size()==0){
                System.out.println("获取发起人流程不成功");
                return CommonResult.success(list);
            }else{
                applicationList.addAll(list);
            }
            return CommonResult.success(applicationList,"获取认领作废流程成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("获取认领作废流程失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("获取认领作废流程失败");
        }
    }

    @Override
    public CommonResult approveClaimAbolish(User user, String flowNote, Integer abolishId){
        try{
            Integer flowId = dkClaimCancelMapper.getFlowIdFromAbolish(abolishId);
            dkClaimCancelMapper.approveClaimAbolish(flowId, flowNote, user.getId(), abolishId);
            xcxInfoService.sendWxMessage(flowId);
            return CommonResult.success(null, "通过认领作废成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("通过认领作废失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("通过认领作废失败");
        }
    }

    @Override
    public CommonResult rejectClaimAbolish(User user, String flowNote, Integer abolishId){
        try{
            Integer flowId = dkClaimCancelMapper.getFlowIdFromAbolish(abolishId);
            dkClaimCancelMapper.rejectClaimAbolish(flowId, flowNote, user.getId(), abolishId);
            return CommonResult.success(null, "拒绝认领作废成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("拒绝认领作废失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("拒绝认领作废失败");
        }
    }

    @Override
    public List<DkContractBean> getClaimTaskContractList(Integer claimTaskId, String searchStr, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        Integer claimId = dkClaimTaskMapper.getClaimTaskData(null, claimTaskId).get(0).getClaimId();
        return dkClaimContractMapper.getClaimTaskContractList(claimTaskId, claimId, searchStr);
    }

    @Override
    public CommonResult claimTaskRelateContract(Integer claimTaskId, Integer contractId){
        try{
            DkClaimTask dkClaimTask = dkClaimTaskMapper.selectByPrimaryKey(claimTaskId);
            dkClaimTask.setContId(contractId);
            dkClaimTaskMapper.updateByPrimaryKeySelective(dkClaimTask);
            return CommonResult.success(null, "认领任务关联合同成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            logService.writeErrorLog("认领任务关联合同失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("认领任务关联合同失败");
        }
    }

    @Override
    public List<DkClaimedBean> getDkClaimedList(BigDecimal invMoney, User user, String searchStr, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum, pageSize);
        return dkClaimMapper.getDkClaimedList(invMoney, user.getCoId(), searchStr);
    }

    @Override
    public SumDkReceiveMoneyBean getSumDkReceiveMoney(Short coId, String searchStr, String monthStr, String bankType) {
        return dkReceiveMapper.getSumDkReceiveMoney(coId, searchStr, monthStr, bankType);
    }

    @Override
    public List<DwmdBean> getScYqmdList(User user, String searchStr, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum, pageSize);
        return dkClaimMapper.getScYqmdList(user.getCoId(), searchStr);
    }

    @Override
    public List<DwmdBean> getYcBmdList(User user, String searchStr, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum, pageSize);
        return dkClaimMapper.getYcBmdList(user.getCoId(), searchStr);
    }

}
